<template>
  <div style="display: flex">
    <div style="width: 400px;margin-right: 5px">
      <el-table
        v-if="null!=deviceCoreList && deviceCoreList.length > 0"
        v-loading="settingLoading"
        :data="deviceQueue"
      >
        <el-table-column :label="$t('deviceCore')" prop="deviceCore"/>
        <el-table-column prop="status" :label="$t('status')" :formatter="fStatus" width="50"/>
        <el-table-column prop="msg" :label="$t('message')"/>
        <el-table-column :label="$t('function')" width="100">
          <template slot-scope="scope">
            <el-button
              v-if="setting"
              type="text"
              @click="retrySend(scope.row)"
            >{{ $t('send') }}
            </el-button>
            <el-button
              style="color: #f56c6c"
              type="text"
              @click="del(scope.row)"
            >{{ $t('delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="flex-grow:1 ">
      <div style="display: flex;justify-content: space-between">
        <el-form :inline="true">
          <el-form-item>
            <div v-if="sensorList.length > 1">
              <div v-if="sensorList.length < 4">
                <el-checkbox-group v-model="choseSensorList" @change="formatDeviceSettingList">
                  <el-checkbox
                    v-for="item in sensorList"
                    :key="item.sensorId"
                    :label="item.sensorId"
                  >
                    <span>{{ $t('port') + item.port }}</span>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <el-select
                v-else
                v-model="choseSensorList"
                multiple
                style="width: 600px"
                @change="formatDeviceSettingList"
              >
                <el-option
                  v-for="item in sensorList"
                  :key="item.port"
                  :label="item.port"
                  :value="item.port"
                >
                  <span style="color: #8492a6; font-size: 13px">[{{ $t('port') + item.port }}]</span>
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="commonGroupByPortDeviceList"
            >{{ $t('search') }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-alert
        v-if="settingLoading"
        :title="$t('loading')"
        type="warning"
        center
        show-icon
        :closable="false"
      />

      <div
        v-for="(sensor,sensorIndex) in showSensorList"
        v-else
        :key="sensorIndex"
      >
        <div
          class="primary-color"
          style="line-height: 40px;font-size:15px;"
        >
          <span>[{{ $t('port') }}:{{ sensor.port }}]</span>
        </div>
        <div
          v-for="(item,index) in sensor.settingList"
          :key="index"
        >
          <div class="item">
            <div
              class="flex justify-between content-center"
              style="margin-bottom: 5px;padding: 8px"
            >
              <div class="flex content-center">
                <el-image
                  style="width:30px;height:30px;margin-right: 8px;padding: 2px"
                  :src="item.iconUrl"
                />
                <div>
                  <div class="text-xs">
                    {{ item.name }}
                  </div>
                  <div class="text-xs">{{ formatDate(item.updateDate) }}</div>
                </div>
              </div>
              <div style="width: 580px">
                <div v-if="item.type === 'fixedParam'">
                  <div v-if="item.paramList.length > 5">
                    <el-select
                      v-model="item.value"
                      filterable
                      :disabled="item.disabled"
                    >
                      <el-option
                        v-for="item2 in item.paramList"
                        :key="item2.value"
                        :label="item2.name + item.unit"
                        :value="item2.value"
                      />
                    </el-select>
                    <el-button
                      type="primary"
                      :disabled="item.disabled"
                      @click.stop="valueChange(item)"
                    >{{ $t('confirm') }}
                    </el-button>
                  </div>
                  <el-button
                    v-for="(item2,index2) in item.paramList"
                    v-else
                    :key="index2"
                    type="primary"
                    :plain="item2.value !== item.value"
                    :disabled="item2.disabled"
                    @click="valueChange(item2)"
                  >{{ item2.name + item.unit }}
                  </el-button>
                </div>
                <div v-else-if="item.type === 'switch'">
                  <el-switch
                    v-model="item.value"
                    :disabled="item.disabled"
                    :active-text="$t('open')"
                    :inactive-text="$t('close')"
                    active-value="1"
                    inactive-value="0"
                    @change="valueChange(item)"
                  />
                </div>
                <div v-else-if="item.type === 'time'">
                  <el-time-picker
                    v-model="item.value"
                    :disabled="item.disabled"
                    style="width:300px"
                    value-format="HH:mm"
                    format="HH:mm"
                    :placeholder="$t('timing')"
                  />
                  <el-button
                    type="primary"
                    :disabled="item.disabled"
                    @click.stop="valueChange(item)"
                  >{{ $t('confirm') }}
                  </el-button>
                </div>
                <div v-else-if="item.type === 'timeSlot'" class="flex">
                  <time-slot v-model="item.value" :disabled="item.disabled"/>
                  <el-button
                    type="primary"
                    :disabled="item.disabled"
                    @click.stop="valueChange(item)"
                  >{{ $t('confirm') }}
                  </el-button>
                </div>
                <div v-else-if="item.type === 'noParam'">
                  <el-button
                    type="primary"
                    :disabled="item.disabled"
                    @click.stop="valueChange(item)"
                  >{{ $t('confirm') }}
                  </el-button>
                </div>
                <div v-else-if="item.type === 'slider'">
                  <el-slider
                    v-model="item.value"
                    style="width:360px"
                    :disabled="item.disabled"
                    @change="switchChange(item)"
                  />
                </div>
                <div v-else-if="item.type === 'multiCustom'" class="flex flex-wrap items-center">
                  <div
                    v-for="(param,paramIndex) in item.valueList"
                    :key="paramIndex"
                    style="margin:0 5px 5px 5px"
                  >
                    <div v-if="param.type === 'switch'">
                      <el-switch
                        v-model="param.value"
                        active-value="1"
                        inactive-value="0"
                        :disabled="item.disabled"
                      />
                    </div>
                    <div v-else-if="param.type === 'time'">
                      <el-time-picker
                        v-model="param.value"
                        :disabled="item.disabled"
                        style="width:100px"
                        value-format="HH:mm"
                        format="HH:mm"
                        :placeholder="$t('timing')"
                      />
                    </div>
                    <div v-else-if="param.type === 'timeSlot'">
                      <time-slot v-model="param.value" :disabled="item.disabled"/>
                    </div>
                    <div v-else-if="param.type === 'slider'">
                      <el-slider
                        v-model="param.value"
                        input-size="mini"
                        :disabled="item.disabled"
                        style="width:200px;"
                      />
                    </div>
                    <div v-else-if="param.type === 'fixedParam'">
                      <el-select
                        v-model="param.value"
                        style="width:100px"
                        :disabled="item.disabled"
                        filterable
                      >
                        <el-option
                          v-for="item2 in item.paramList"
                          :key="item2.value"
                          :label="item2.name + item.unit"
                          :value="item2.value"
                        />
                      </el-select>
                    </div>
                    <el-input
                      v-else
                      v-model="param.value"
                      style="width:55px"
                      :disabled="item.disabled"
                    >
                      <template v-if="item.unit" slot="append">{{ item.unit }}</template>
                    </el-input>
                  </div>
                  <el-button
                    style="margin:0 5px 5px 5px"
                    type="primary"
                    :disabled="item.disabled"
                    @click.stop="valueChange(item)"
                  >{{ $t('confirm') }}
                  </el-button>
                </div>
                <div v-else="">
                  <el-input
                    v-model="item.value"
                    style="width:300px"
                    :disabled="item.disabled"
                  >
                    <template v-if="item.unit" slot="append">{{ item.unit }}</template>
                  </el-input>
                  <el-button
                    type="primary"
                    :disabled="item.disabled"
                    @click.stop="valueChange(item)"
                  >{{ $t('confirm') }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  cancelNotice,
  formatDate,
  formatDeviceSetting
} from '@/util/common'
import {
  sendDeviceSetting,
  commonGroupByPortDeviceList
} from '@/api/iot/iotDeviceSettingApi'
import {
  getShowHidden
} from '@/util/storage'
import TimeSlot from '@/components/TimeSlot'

export default {
  name: 'DeviceSetting',
  components: {
    TimeSlot
  },
  props: {
    port: {
      type: String,
      default: null
    },
    deviceCoreList: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      choseSensorList: [],
      sensorList: [],
      showSensorList: [],
      setting: null,
      settingLoading: false,
      deviceQueue: [],
      showHidden: getShowHidden()
    }
  },
  watch: {
    port: {
      deep: true,
      handler(val) {
        this.init()
      }
    },
    deviceCoreList: {
      deep: true,
      handler(val) {
        this.init()
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.commonGroupByPortDeviceList()
      const deviceQueue = []
      if (this.deviceCoreList != null && this.deviceCoreList.length > 0) {
        for (let i = 0; i < this.deviceCoreList.length; i++) {
          deviceQueue.push({
            deviceCore: this.deviceCoreList[i],
            status: 0,
            msg: this.$t('unKnow')
          })
        }
        this.deviceQueue = deviceQueue
      }
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    fStatus(item) {
      if (item.status > 1) {
        return this.$t('failure')
      } else if (item.status === 0) {
        return this.$t('unKnow')
      } else {
        return this.$t('success')
      }
    },
    del(item) {
      const that = this
      this.$confirm(this.$t('delete'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          for (let i = 0; i < that.deviceQueue.length; i++) {
            if (item.deviceCore === that.deviceQueue[i].deviceCore) {
              that.deviceQueue.splice(i, 1)
            }
          }
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    valueChange(item) {
      this.setting = item
      if (this.setting.type === 'multiCustom') {
        let value = ''
        this.setting.valueList.forEach(v => {
          if (value === '') {
            value = v.value
          } else {
            value = value + ',' + v.value
          }
        })
        this.setting.value = value
      }
      this.updateVal()
    },
    commonGroupByPortDeviceList() {
      this.sensorList = []
      const json = {
        deviceCoreList: this.deviceCoreList,
        hidden: this.showHidden === '1' ? null : false
      }
      commonGroupByPortDeviceList(json).then(res => {
        const { code, data } = res
        if (code === '200') {
          const sensorList = []
          for (let i = 0, j = data.length; i < j; i++) {
            const sensor = data[i]
            if (!sensor.settingList || sensor.settingList.length === 0) {
              continue
            }
            sensorList.push(sensor)
            if (this.port) {
              this.choseSensorList = [this.port]
            } else {
              this.choseSensorList.push(sensor.port)
            }
          }
          this.sensorList = sensorList
          this.formatDeviceSettingList()
        }
      })
    },
    formatDeviceSettingList() {
      const showSensorList = []
      for (let n = 0, m = this.sensorList.length; n < m; n++) {
        const sensor = this.sensorList[n]
        if (!this.choseSensorList || !this.choseSensorList.includes(sensor.port)) {
          continue
        }
        const settingList = []
        for (let i = 0, j = sensor.settingList.length; i < j; i++) {
          let setting = {
            ...sensor.settingList[i]
          }
          if (this.name) {
            if (setting.name.indexOf(this.name) < 0) {
              continue
            }
          }
          setting = formatDeviceSetting(setting)
          settingList.push(setting)
        }
        if (!sensor.settingList || sensor.settingList.length === 0) {
          continue
        }
        showSensorList.push({
          port: sensor.port,
          settingList: settingList
        })
      }
      this.showSensorList = showSensorList
    },
    updateVal() {
      this.sendList(0)
    },
    retrySend(item) {
      this.deviceCore = item.deviceCore
      this.sendDeviceSetting().then(res => {
        this.responseFun(this, res, true)
      })
    },
    sendList(i) {
      this.deviceCore = this.deviceQueue[i].deviceCore
      this.sendDeviceSetting().then(res => {
        this.responseFun(this, res, true)
        this.sendList(i + 1)
      })
    },
    sendDeviceSetting() {
      this.settingLoading = true
      const that = this
      return new Promise(function(resolve, reject) {
        const json = {
          tag: 'manage',
          keyName: that.setting.keyName,
          value: that.setting.value,
          port: that.setting.port,
          deviceCore: that.deviceCore
        }
        sendDeviceSetting(json).then(res => {
          resolve(res)
        })
      })
    },
    responseFun(that, res) {
      const { code, msg } = res
      that.settingLoading = false
      let status = 0
      if (code === '200') {
        status = 1
      } else {
        status = 2
      }

      for (let i = 0; i < that.deviceQueue.length; i++) {
        if (that.deviceQueue[i].deviceCore !== this.deviceCore) {
          continue
        }
        const item = {
          deviceCore: that.deviceQueue[i].deviceCore,
          status: status,
          msg: msg
        }
        that.deviceQueue.splice(i, 1, item)
      }
    }
  }

}
</script>
<style scoped lang="scss">
@import '@/styles/element-variables.scss';

.primary-color {
  color: $--color-primary;
}

.item:hover {
  background-color: #ebeef5;
  border-radius: 14px;
}
</style>

